package org.nf.web.initializer;

import jakarta.servlet.DispatcherType;
import jakarta.servlet.FilterRegistration;
import jakarta.servlet.ServletContext;
import org.nf.web.WebApplicationInitializer;
import org.nf.web.config.Configure;
import org.nf.web.config.MvcConfig.CorsConfig;
import org.nf.web.filter.CorsFilter;

import java.util.EnumSet;

public class CorsFilterInitializer implements WebApplicationInitializer {

    private final static String FILTER_NAME = "cors";

    @Override
    public void onStartup(ServletContext servletContext) {
        initCorsFilter(servletContext);
    }

    private void initCorsFilter(ServletContext servletContext) {
        Configure config = (Configure) servletContext.getAttribute(Configure.class.getName());
        CorsConfig corsConfig = config.getMvc().getCors();
        if(corsConfig.getEnable()) {
            CorsFilter filter = new CorsFilter();
            filter.setAllowedOrigins(corsConfig.getAllowedOrigins());
            filter.setAllowedHeaders(corsConfig.getAllowedHeaders());
            filter.setAllowedMethods(corsConfig.getAllowedMethods());
            filter.setExposedHeaders(corsConfig.getExposedHeaders());
            filter.setAllowCredentials(corsConfig.getAllowCredentials());
            filter.setMaxAge(corsConfig.getMaxAge());
            FilterRegistration.Dynamic registration = servletContext.addFilter(FILTER_NAME, filter);
            registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, corsConfig.getMapping());
        }
    }
}
